package com.bbcare.followup.plat.task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.util.CollectionUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.SeqUtil;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.service.IPatientService;

/**
 * @name: 患者任务过期处理类
 * @author: DemonLee
 * @createTime: 2017.5.6
 * @description: 将患者过期任务统一修改为失访状态，目前该任务后台每2小时运行一次
 * @modify:
 * 
 */
public class PatientTaskExpiredTask implements Job{

    private final Log logger = LogFactory.getLog(PatientTaskExpiredTask.class);

    @Autowired
    private IPatientService patientSerivce;

    @Override
    public void execute(JobExecutionContext context){
        logger.warn("---start: PatientTaskExpiredTask---"+DateUtil.getMillSysDate());

        List<PatientTask> epList = null;

        Map<String, Object> paramIn = new HashMap<String, Object>();
        paramIn.put("start", 0);
        paramIn.put("end", 100);// 每次提取100条
        paramIn.put("taskStatus", Constants.PATIENT_TASK_STATUS_INIT);// 未开始的任务
        paramIn.put("expiredTime", DateUtil.getCurrDateByDay(1, Constants.SUBTRACT_CHAR));// 截止时间=昨天
        paramIn.put("opCode", Constants.OP_CODE_3001);
        paramIn.put("opType", Constants.OP_TYPE_BG_ADMIN);
        paramIn.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);// 队列中正常状态下的用户
        List<String> taskTypeInList = new ArrayList<String>();
        taskTypeInList.add(Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务
        taskTypeInList.add(Constants.TASK_TYPE_SCHEME_TEMP);// 线上随访
        paramIn.put("taskTypeIn", taskTypeInList);
        String authorId = Constants.BG_LOGIN_NO_ADMIN;// 后台程序处理工号
        int totalNum = 0;

        while (true) {
            try {
                epList = patientSerivce.getPatientExpieredTaskList(paramIn);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return;
            }

            if (!CollectionUtils.isEmpty(epList)) {
                Map<String, Object> dealIn = new HashMap<String, Object>();
                PatientTask ptVo = new PatientTask();
                int iep = epList.size();
                int k = 0;
                for (k = 0; k < iep; k++) {
                    dealIn.clear();
                    ptVo = epList.get(k);
                    dealIn.put("taskId", ptVo.getId());
                    dealIn.put("userId", ptVo.getUserId());
                    dealIn.put("taskName", ptVo.getTaskName());
                    dealIn.put("ptSchemeId", ptVo.getPtSchemeid());
                    dealIn.put("queueId", ptVo.getQueueId());
                    dealIn.put("authorId", authorId);
                    dealIn.put("taskType", ptVo.getTaskType());
                    dealIn.put("updateTime", DateUtil.getTimeString(DateUtil.getSysDateA()));
                    dealIn.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
                    dealIn.put("opCode", Constants.OP_CODE_3001);
                    dealIn.put("opType", Constants.OP_TYPE_BG_ADMIN);

                    try {
                        patientSerivce.dealPatientExpieredTask(dealIn);
                        totalNum++;
                    } catch (AppException e) {
                        // TODO Auto-generated catch block
                        logger.error("dealPatientExpieredTask AppException...dealIn==" + dealIn.toString());
                        e.printStackTrace();

                        // 将错误记录存在异常表pt_excp_rd中，后续查询过滤掉这批数据
                        try {
                            dealIn.put("errMsg", e.getErrMsg());
                            patientSerivce.savePtExcpInfo(dealIn);
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            logger.error("---savePtExcpInfo AppException---dealIn==" + dealIn.toString());
                            e1.printStackTrace();
                            // 这里再报错，可能会出现死循环，后续补
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        logger.error("dealPatientExpieredTask Exception...dealIn==" + dealIn.toString());
                        e.printStackTrace();

                        // 将错误记录存在异常表pt_excp_rd中，后续查询过滤掉这批数据
                        try {
                            dealIn.put("errMsg", "dealPatientExpieredTask Exception:" + e.getMessage());
                            patientSerivce.savePtExcpInfo(dealIn);
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            logger.error("---savePtExcpInfo Exception---dealIn==" + dealIn.toString());
                            e1.printStackTrace();
                            // 这里再报错，可能会出现死循环，后续补
                        }
                    }
                }
            } else {
                break;
            }
        }

        logger.warn("---end: PatientTaskExpiredTask---total deal==" + totalNum);

        return;
    }
}
